package org.yray.yaml;

import cn.hutool.core.io.FileUtil;
import org.yaml.snakeyaml.Yaml;
import org.yray.yaml.utils.FileUtils;

import java.io.*;
import java.util.List;
import java.util.Map;

public class YamlObject {

    private  Map sourceMap ;
    private Yaml yaml ;

    public YamlObject(String fileName)
    {
        yaml = new Yaml();
        try {
            sourceMap= yaml.loadAs(new FileInputStream(new File(fileName)),Map.class);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void setVal(String key,Object val)
    {
        String[] keys=key.split("\\.");
        Map tempMap=sourceMap;
        setValByList(keys,val,tempMap,0);
    }

    public void setValByList(String[] keys,Object val,Map previousMap,int currIndex)
    {
        if(keys.length==currIndex+1)
        {
            previousMap.put(keys[currIndex],val);
        }
        else
        {
            Object obj=previousMap.get(keys[currIndex]);
            if(obj instanceof Map) {
                Map temp = (Map)obj;
                setValByList(keys, val, temp, currIndex + 1);
            }
            else if(obj instanceof List)
            {
                List list=(List) obj;
                Map temp =(Map) list.get(0);
                setValByList(keys, val, temp, currIndex + 1);
            }
        }
    }

    public void saveFile(String fileName)
    {
        try {
           String fileCont= yaml.dumpAsMap(sourceMap);
            FileUtil.writeString(fileCont,new File(fileName),"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
